<template>
  <div class="upload" :style="props.imgType == 0 ? 'padding: 16px;' : 'padding: 0;'">
    <div class="title" v-if="props.imgType == 0">
      <span v-if="props.isRequir"style="color: #ee0a24; margin-right: 2px">*</span>
      <span>{{ data?.titelTextvalue }}</span>
    </div>
    <div class="fileList" v-if="props.imgType == 0">
      <van-image v-for="(img, index) in props.fileList" @click="imgPreview(index)" :key="index" width="109" height="109"
        style="margin-top: 8px" :style="[
    (index + 1) % 3 == 0 ? 'margin-right: 0px' : 'margin-right: 8px',
  ]" :src="img">
        <img class="delImg" src="../../assets/images/delImg.png" alt="" @click.stop="delImg(index)" />
      </van-image>
      <van-uploader v-if="props.fileList.length < maxCount" :after-read="afterRead" result-type="file"
        style="margin-top: 8px" />
    </div>
    <div v-else style="display: flex; flex-wrap: wrap">
      <van-image v-for="(img, index) in props.fileList" @click="imgPreview(index)" :key="index"
        style="width: 6.8125rem; height: 6.8125rem" :style="[
    (index + 1) % 3 == 0 ? 'margin-right: 0px' : 'margin-right: 4px',
    index > 2 ? 'margin-top: 4px' : '',
  ]" :src="img">
      </van-image>
    </div>
  </div>
</template>

<script setup name="file">
import { showNotify, showSuccessToast, showImagePreview } from 'vant'
const emit = defineEmits(['fileListFun'])
const { usePublic } = $globalStore
const props = defineProps({
  fileType: {
    type: Boolean,
    default: 0,
  },
  titelText: {
    type: String,
    default: '',
  },
  fileList: {
    type: Array,
    default: [],
  },
  imgType: {
    type: Number,
    default: 0,
  },
  maxCount: {
    type: Number,
    default: 3,
  },
  isRequir: {
    type: Boolean,
    default:true
  }
})

const data = reactive({
  fileType: props?.fileType,
  titelTextvalue: props?.titelText,
})

const afterRead = async (file) => {
  // 此时可以自行将文件上传至服务器
  console.log(file)
  const res = await usePublic.uploadFile({ file: file.file }, data.fileType)
  if (res.code == 0) {
    showSuccessToast('上传成功')
    props.fileList.push(res.data.fileIds[0])
    emit('fileListFun', props.fileList)
  }
}

const delImg = (index) => {
  props.fileList.splice(index, 1)
  emit('fileListFun', props.fileList)
}

const imgPreview = (index) => {
  console.log(props.fileList)
  showImagePreview({
    images: props.fileList,
    startPosition: index,
  })
}
</script>

<style lang="scss" scpoed>
.upload {
  .fileList {
    display: flex;
    flex-wrap: wrap;
    align-items: flex-start;

    // .imgs {
    //   margin-right: 8px;
    // }
  }
}

.van-image {
  position: relative;

  .delImg {
    position: absolute;
    width: 20px;
    height: 20px;
    top: 0;
    right: 0;
    border-radius: 0 4px 0 0;
  }
}
</style>
